<template>
    <div class="choujiang-container">
        <div id="qt">
            <div id="qrCode">
                <h1 style="color: white;font-size: x-large;">川邮.计网.国际班【毕业幸运轮】</h1>
                <br><img src="/jiafen.png" title="长按可以清除抽奖名单" @mousedown="startPressTimer" @mouseup="cancelPressTimer"
                    @mouseleave="cancelPressTimer" @touchstart="startPressTimer" @touchend="cancelPressTimer" />
            </div>
            <div id="controller">
                <label for="huojiangren">获奖人:</label>
                <div id="huojiangren">{{ winners }}</div>
                <button id="startButton" :disabled="isButtonDisabled" @click="handleButtonClick">
                    {{ buttonText }}
                </button>
            </div>
        </div>

        <div id="xs">
            <div id="container">
                <div v-for="(student, index) in students" :key="index" class="student-item"
                    :class="{ highlight: index === currentIndex }">
                    <div v-html="student"></div>
                </div>
            </div>
        </div>

        <!-- 自定义弹窗 -->
        <div id="customPopup" :style="{ display: isPopupVisible ? 'flex' : 'none' }">
            <div id="popupContent">
                <h3>恭喜您！</h3>
                <p id="popupMessage">{{ popupMessage }}</p>
                <button id="popupCloseButton" @click="closePopup">关闭</button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { apiClient } from '@/utils/apiClient';
import { onMounted, onUnmounted, ref } from 'vue';

// 响应式数据
const students = ref([]);
const currentIndex = ref(-1);
const isButtonDisabled = ref(true);
const buttonText = ref('等待连接');
const winners = ref('');
const isPopupVisible = ref(false);
const popupMessage = ref('');

// 长按相关变量
const pressTimer = ref(null);

// WebSocket重连相关变量
const reconnectAttempts = ref(0);
const maxReconnectAttempts = ref(5);
const reconnectInterval = ref(3000); // 3秒

// 抽奖相关变量
const startDelay = 20;
let delay = startDelay;
let clickNum = 0;
let intervalId = null;
const enteredTexts = [];
let socket = null;
let zhongjiangIndex = 0;

// 处理按钮点击事件
const handleButtonClick = () => {
    if (clickNum === 0) {
        buttonText.value = "停止转动";
        isButtonDisabled.value = false;
        doIt();
    } else {
        buttonText.value = "正在减速...";
        isButtonDisabled.value = true;
    }
    clickNum++;
};

// 开始长按计时
const startPressTimer = () => {
    cancelPressTimer(); // 清除之前的定时器
    pressTimer.value = setTimeout(() => {
        clearChoujiang();
    }, 1000); // 长按1秒触发
};

// 取消长按计时
const cancelPressTimer = () => {
    if (pressTimer.value) {
        clearTimeout(pressTimer.value);
        pressTimer.value = null;
    }
};

// 调用清除抽奖记录接口
const clearChoujiang = async () => {
    if (!confirm('确定要清除抽奖记录吗？')) {
        return;
    }
    try {
        await apiClient.get('/api/records/clearchoujiang');
        students.value = [];//清空列表
        alert('抽奖记录已清除');
    } catch (error) {
        console.error('清除抽奖记录失败:', error);
        alert('清除抽奖记录失败: ' + error.message);
    }
};

// 执行抽奖动画
const doIt = () => {
    if (intervalId) {
        clearInterval(intervalId);
    }

    intervalId = setInterval(() => {
        if (students.value.length === 0) return;

        // 更新当前高亮索引
        currentIndex.value = (currentIndex.value + 1) % students.value.length;

        if (clickNum > 1) {
            delay *= 1.08;
        }

        if (delay >= 1000) {
            clearInterval(intervalId);
            intervalId = null;

            // 添加中奖者
            appendZhongjiang(students.value[currentIndex.value]);

            buttonText.value = "抽奖成功";

            setTimeout(() => {
                clickNum = 0;
                delay = startDelay;
                buttonText.value = "开始幸运轮";
                isButtonDisabled.value = false;

                // 从学生列表中移除中奖者
                students.value.splice(currentIndex.value, 1);

                // 重置索引
                currentIndex.value = -1;
            }, 2000);
        }
    }, delay);
};

// 添加中奖者
const appendZhongjiang = (namesn) => {
    const nameAndSn = namesn.split("<br>");
    winners.value += `  ${nameAndSn[0]} 、`;
    zhongjiangIndex++;
    showPopup(nameAndSn[0] + "(" + nameAndSn[1] + ")");
};

// 显示弹窗
const showPopup = (name) => {
    popupMessage.value = `恭喜 ${name} 中奖！`;
    isPopupVisible.value = true;
};

// 关闭弹窗
const closePopup = () => {
    isPopupVisible.value = false;
};

// 改进WebSocket连接处理，添加重连机制
const connectWebSocket = () => {
    let url = "";
    if (window.location.href.indexOf("https://") === 0) {
        url = 'wss://' + window.location.host + '/ws/loadPersons';
    } else {
        url = 'ws://' + window.location.host + '/ws/loadPersons';
    }
    // url = 'ws://localhost:8080/ws/loadPersons';

    socket = new WebSocket(url);

    socket.onopen = () => {
        console.log("WebSocket连接已建立");
        buttonText.value = "开始幸运轮";
        isButtonDisabled.value = false;

        // 重置连接尝试计数
        reconnectAttempts.value = 0;
    };

    socket.onmessage = (event) => {
        if (event.data && event.data.length > 0) {
            if (event.data.startsWith("clearAll")) {
                students.value = [];
                enteredTexts.length = 0;
                // 清空 enteredTexts
                return;
            }
            const sn = event.data.split("<br>");
            if (enteredTexts.includes(sn[1])) {
                return;
            }

            enteredTexts.push(sn[1]);
            students.value.push(event.data);
        }
    };

    socket.onclose = (event) => {
        console.log("WebSocket连接已关闭:", event.code, event.reason);
        buttonText.value = '连接已关闭';
        isButtonDisabled.value = true;

        // 实现重连机制
        if (reconnectAttempts.value < maxReconnectAttempts.value) {
            reconnectAttempts.value++;
            setTimeout(() => {
                console.log(`尝试重连 (${reconnectAttempts.value}/${maxReconnectAttempts.value})`);
                connectWebSocket();
            }, reconnectInterval.value);
        }
    };

    socket.onerror = (error) => {
        console.error('WebSocket发生错误:', error);
        buttonText.value = '发生错误: ' + error.message;
        isButtonDisabled.value = true;
    };
};

// 组件挂载时建立WebSocket连接
onMounted(() => {
    // 添加重连机制
    connectWebSocket();
});

// 组件卸载时清理资源
onUnmounted(() => {
    if (socket) {
        socket.close();
    }
    if (intervalId) {
        clearInterval(intervalId);
    }
    cancelPressTimer(); // 清理长按定时器
});
</script>

<style scoped>
.choujiang-container {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: flex-start;
    height: 100vh;
    margin: 0;
    font-family: Arial, sans-serif;
    background: linear-gradient(to bottom, #0c0d19, #3800ccf5);
    color: white;
}

#qt {
    width: 30%;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
}

#qrCode {
    text-align: center;
    position: fixed;
    top: 5px;
    left: 10px;
}

#qrCode img {
    width: 300px;
    height: 300px;
}

#controller {
    position: fixed;
    bottom: 10px;
    left: 10px;
    font-size: 24px;
    width: 30%;
}

#controller div {
    margin: 10px 0;
}

#startButton {
    padding: 10px 20px;
    font-size: 24px;
    background-color: #ff0000;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    height: 70px;
    width: 50%;
    margin-top: 5px;
}

#startButton:disabled {
    background-color: gray;
    cursor: not-allowed;
}

#xs {
    width: 70%;
    padding: 20px;
    overflow-y: auto;
}

#container {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
    max-width: 100%;
    margin: 20px auto;
}

.student-item {
    width: 95px;
    height: 40px;
    border: 1px solid #ccc;
    display: flex;
    font-size: 14px;
    justify-content: center;
    text-align: center;
    align-items: center;
    margin-bottom: 25px;
    padding: 5px;
    margin-left: 5px;
    background-color: #f9f9f9;
    color: #333;
    border-radius: 5px;
}

.student-item.highlight {
    background-color: #FFD700;
    color: black;
}

/* 自定义弹窗样式 */
#customPopup {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    justify-content: center;
    align-items: center;
    z-index: 1000;
    animation: fadeIn 0.5s ease-out;
}

#popupContent {
    background: linear-gradient(135deg, #ff6347, #ff4500, #ff1493);
    color: white;
    padding: 30px;
    border-radius: 15px;
    box-shadow: 0 0 30px rgba(0, 0, 0, 0.5);
    width: 400px;
    height: 300px;
    text-align: center;
    transform: scale(0);
    animation: popupAnimation 1s forwards;
}

#popupContent h3 {
    font-size: 30px;
    font-weight: bold;
    margin: 20px 0;
}

#popupMessage {
    font-size: 35px;
    margin-bottom: 20px;
    font-weight: 900;
}

#popupCloseButton {
    padding: 12px 24px;
    background-color: #ffcc00;
    color: black;
    font-weight: bold;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 18px;
    transition: all 0.3s ease;
    margin-top: 50px;
    height: 60px;
    width: 120px;
}

#popupCloseButton:hover {
    background-color: #ffb300;
    transform: scale(1.05);
}

#huojiangren {
    height: 200px;
    width: 100%;
}

/* 动画效果 */
@keyframes fadeIn {
    from {
        opacity: 0;
    }

    to {
        opacity: 1;
    }
}

@keyframes popupAnimation {
    from {
        transform: scale(0);
    }

    to {
        transform: scale(1);
    }
}

@keyframes fadeInMessage {
    from {
        opacity: 0;
    }

    to {
        opacity: 1;
    }
}
</style>
